import React,{useEffect,useState,useRef} from 'react';
import { Card, Col, Row,Avatar,List, Drawer  } from 'antd'
import axios from 'axios'
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import * as Echarts from 'echarts'
import _ from 'lodash'
const { Meta } = Card;
const Home = () => {
  const [fabulous, setfabulous] = useState([])
  const [browse, setbrowse] = useState([])
  const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem('token'))
  const mainRef = useRef(null)
  const [visible, setvisible] = useState(false)
  const pieChartRef = useRef(null)
  const [priBar, setpriBar] = useState(null)
  const [priList, setpriList] = useState([])
  
  // 用户常浏览
  useEffect(() => {
    axios.get('/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6').then(res => {
      setbrowse(res.data)
    })
  }, [])

  // 点赞最多
  useEffect(() => {
    axios.get('/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6').then(res => {
     setfabulous(res.data)
   })
  }, []);

  // 图表数据
  useEffect(() => {
    axios.get('/news?publishState=2&_expand=category').then(res => {
      echartsInit(_.groupBy(res.data, item => item.category.title))
      setpriList(res.data)
    })
     return () => {
        window.onresize = null
      }
  }, []);

  // 饼图
  const pieChart = () => {
    const {username} = JSON.parse(localStorage.getItem('token'))
    var option;
    var myChart
    if (!priBar) {
      myChart = Echarts.init(pieChartRef.current)
      setpriBar(myChart)
    } else{
       myChart=priBar
    }
    let arr1 = priList.filter(item => item.author === username)
    let arr2 = _.groupBy(arr1, item => item.category.title)
    let arr3 = []
    for (let key in arr2) {
      arr3.push({
        name: key,
        value: arr2[key].length
      })
    }
    option = {
      title: {
        text: '当前用户新闻分类图示',
        subtext: `用户：${username}`,
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '发布数量',
          type: 'pie',
          radius: '50%',
          data:arr3,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };

    option && myChart.setOption(option);
  }
  // 柱图初始化
  const echartsInit = (obj) => {
      var myChart = Echarts.init(mainRef.current, null, {
      height: 400
    });
   var option = {
        title: {
          text: '新闻分类图示'
        },
        tooltip: {},
        legend: {
          data: ['数量']
        },
        xAxis: {
          data: Object.keys(obj),
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
           minInterval: 1
        },
        series: [
          {
            name: '数量',
            type: 'bar',
            data: Object.values(obj).map(item=>item.length)
          }
        ]
      };

      // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
    window.onresize = () => {
      console.log(65464646)
      myChart.resize()
    }
  }
  return (
   <div className="site-card-wrapper">
    <Row gutter={16}>
      <Col span={8}>
        <Card title="用户最常浏览" bordered={true}>
          <List
            size="large"
            dataSource={browse}
            renderItem={item => (
               <List.Item>
                <a href={`#/news-manage/preview/${item.id}`}>{ item.title }</a>
              </List.Item>
            )}
          />
        </Card>
      </Col>
      <Col span={8}>
        <Card title="用户点赞最多" bordered={true}>
          <List
            size="large"
            dataSource={fabulous}
            renderItem={item => (
              <List.Item>
                <a href={`#/news-manage/preview/${item.id}`}>{ item.title }</a>
              </List.Item>
            )}
          />
        </Card>
      </Col>
      <Col span={8}>
        <Card
          cover={
            <img
              alt="example"
              src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
            />
          }
          actions={[
            <SettingOutlined key="setting" onClick={() => {
              setvisible(true)
              setTimeout(() => {
                pieChart()
              },0)
            }}/>,
            <EditOutlined key="edit" />,
            <EllipsisOutlined key="ellipsis" />,
          ]}
        >
          <Meta
            avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
            title={username}
              description={
                <div>
                  <b>{region?region:'全球'}</b>
                  <span style={{paddingLeft:'30px'}}>{roleName}</span>
                </div>
            }
          />
        </Card>
      </Col>
      </Row>

       <Drawer title="个人新闻发布" width="500px" placement="right" onClose={()=>{ setvisible(false)}} visible={visible}>
          <div ref={pieChartRef} style={{
          width: "100%",
          height: "400px",
          marginTop: '50px',
        }}></div>
      </Drawer>
      {/* 图表 */}
      <div ref={mainRef} style={{
        width: "100%",
        height: "500px",
        marginTop: '30px',
        paddingTop: "30px"
      }}></div>
  </div>
  );
}

export default Home;
